const baseUrl = "http://localhost:8080";

const httpGet = (url,data,headers) => request(url,'GET',data,headers);
const httpPost = (url,data,headers) => request(url,'POST',data,headers);
const httpPut = (url,data,headers) => request(url,'PUT',data,headers);
const httpDelete = (url,data,headers) => request(url,'DELETE',data,headers);

//url是请求地址，data是请求参数，header是请求头 ，method是请求方法
const request = (url,method,data,headers) => {
  if(!url.startsWith('/')){
    url = `/${url}`;
  }
      //返回一个异步方法
      //resolve：成功时会通过，then接受或者async -await得到
      //reject，异常时，.catch接收
    return new Promise((resolve,reject) => {
        wx.request({
          url: baseUrl + url, 
          method,
          header:{
            [ wx.getStorageSync('tokenName') || 'Authorization'] :wx.getStorageSync('token') || '',
            ...headers
          },
          data,
          success: ({data}) => {
            if(data.code == 200){
              resolve(data);
            }else{
              wx.showToast({
                title: data.message,
                icon:'error'
              });
              reject(data.message)
            }
          },
          fail:(err) => {
            wx.showToast({
              title: err.errMsg,
              icon:'error'
            });
              reject(err);
          }
        })
    });
}
//封装上传的地址
const upload = (filePath) => {
  return new Promise((resolve,reject) => {
    wx.uploadFile({
      filePath,
      name: 'file',
      url: baseUrl + '/common/upload',
      success: ({data}) => {
        if(data.code == 200){
          resolve(data);
        }else{
          wx.showToast({
            title: data.message,
            icon:'error'
          });
          reject(data.message)
        }
      },
      fail:(err) => {
        wx.showToast({
          title: err.errMsg,
          icon:'error'
        });
          reject(err);
      }
    })
});
}

//获取图片预览地址
const fileView = (filename) =>{
  if(filename){
    if(filename.startsWith('http')){
      return filename;
    }
    return `${baseUrl}/common/view/${filename}`;
  }
  return '';
}

export {
  httpGet,
  httpPost,
  httpPut,
  httpDelete,
  upload,
  fileView
}
